// 装备套装系统 - 深度策略收集机制
(function() {
    'use strict';
    
    class EquipmentSetSystem {
        constructor() {
            this.playerInventory = [];
            this.equippedItems = {};
            this.activeSets = [];
            this.availableSets = [];
            this.dropRates = {
                common: 0.6,
                rare: 0.25,
                epic: 0.12,
                legendary: 0.03
            };
            
            this.initializeEquipmentSets();
        }
        
        initialize() {
            console.log('⚔️ 装备套装系统已激活');
            this.loadPlayerInventory();
            this.startEquipmentDrops();
            this.setupInventoryUI();
        }
        
        initializeEquipmentSets() {
            this.availableSets = [
                {
                    id: 'survivor_set',
                    name: '幸存者套装',
                    description: '专为长期生存设计的装备',
                    items: ['survivor_helmet', 'survivor_armor', 'survivor_boots'],
                    bonuses: {
                        2: {
                            name: '坚韧意志',
                            description: '生命值+50，生命回复+2/秒',
                            effect: () => this.applySurvivorSet2()
                        },
                        3: {
                            name: '末日求生',
                            description: '所有伤害-30%，移动速度+25%，死亡时恢复50%生命值',
                            effect: () => this.applySurvivorSet3()
                        }
                    },
                    rarity: 'rare'
                },
                {
                    id: 'berserker_set',
                    name: '狂战士套装',
                    description: '为战斗而生的血腥装备',
                    items: ['berserker_mask', 'berserker_armor', 'berserker_gauntlets'],
                    bonuses: {
                        2: {
                            name: '嗜血渴望',
                            description: '攻击速度+40%，击杀回血+15',
                            effect: () => this.applyBerserkerSet2()
                        },
                        3: {
                            name: '无尽怒火',
                            description: '伤害+100%，生命值越低伤害越高(最高+200%)，免疫恐惧',
                            effect: () => this.applyBerserkerSet3()
                        }
                    },
                    rarity: 'epic'
                },
                {
                    id: 'shadow_set',
                    name: '暗影套装',
                    description: '隐秘刺客的完美装备',
                    items: ['shadow_hood', 'shadow_cloak', 'shadow_boots'],
                    bonuses: {
                        2: {
                            name: '暗影步法',
                            description: '闪避冷却-50%，移动速度+30%',
                            effect: () => this.applyShadowSet2()
                        },
                        3: {
                            name: '暗杀精通',
                            description: '背后攻击暴击率100%，暴击伤害+300%，隐身3秒冷却',
                            effect: () => this.applyShadowSet3()
                        }
                    },
                    rarity: 'epic'
                },
                {
                    id: 'elemental_set',
                    name: '元素法师套装',
                    description: '掌控元素力量的神秘装备',
                    items: ['elemental_hat', 'elemental_robe', 'elemental_staff'],
                    bonuses: {
                        2: {
                            name: '元素亲和',
                            description: '攻击附加随机元素效果（火焰/冰霜/雷电）',
                            effect: () => this.applyElementalSet2()
                        },
                        3: {
                            name: '元素风暴',
                            description: '释放元素风暴，大范围伤害+元素效果',
                            effect: () => this.applyElementalSet3()
                        }
                    },
                    rarity: 'legendary'
                },
                {
                    id: 'tech_set',
                    name: '科技战士套装',
                    description: '未来科技与现代战斗的结合',
                    items: ['tech_helmet', 'tech_exosuit', 'tech_boots'],
                    bonuses: {
                        2: {
                            name: '科技增强',
                            description: '弹药容量+100%，装弹速度+100%',
                            effect: () => this.applyTechSet2()
                        },
                        3: {
                            name: '战术系统',
                            description: '自动瞄准，穿透射击，能量护盾',
                            effect: () => this.applyTechSet3()
                        }
                    },
                    rarity: 'legendary'
                }
            ];
        }
        
        startEquipmentDrops() {
            // 增强现有的装备掉落系统
            const originalDropEquipment = window.gameEnhancements?.environmentSystem?.dropRandomEquipment;
            
            if (originalDropEquipment) {
                window.gameEnhancements.environmentSystem.dropRandomEquipment = () => {
                    if (Math.random() < 0.3) { // 30%概率掉落套装装备
                        this.dropSetEquipment();
                    } else {
                        originalDropEquipment.call(window.gameEnhancements.environmentSystem);
                    }
                };
            }
            
            // 定期掉落套装装备
            setInterval(() => {
                if (window.gameEngine?.gameState === 'playing' && Math.random() < 0.1) {
                    this.dropSetEquipment();
                }
            }, 25000);
        }
        
        dropSetEquipment() {
            try {
                if (!window.gameEngine?.powerUps) return;
                
                const rarity = this.selectRarity();
                const availableItems = this.getAllEquipmentItems();
                const item = availableItems[Math.floor(Math.random() * availableItems.length)];
                
                const equipment = {
                    x: Math.random() * 700 + 150,
                    y: Math.random() * 500 + 150,
                    width: 25,
                    height: 25,
                    type: 'set_equipment',
                    itemId: item.id,
                    itemName: item.name,
                    setId: item.setId,
                    rarity: rarity,
                    collected: false,
                    glowEffect: true,
                    isSetItem: true
                };
                
                window.gameEngine.powerUps.push(equipment);
                
                window.gameEnhancements?.visualEffects?.createEquipmentDropEffect(
                    equipment.x, equipment.y, rarity, '⚔️'
                );
                
                console.log(`⚔️ 套装装备掉落: ${item.name} (${rarity})`);
                
            } catch (error) {
                console.error('套装装备掉落失败:', error);
            }
        }
        
        getAllEquipmentItems() {
            const items = [];
            this.availableSets.forEach(set => {
                set.items.forEach(itemId => {
                    items.push({
                        id: itemId,
                        name: this.getItemDisplayName(itemId),
                        setId: set.id,
                        setName: set.name
                    });
                });
            });
            return items;
        }
        
        getItemDisplayName(itemId) {
            const names = {
                // 幸存者套装
                survivor_helmet: '幸存者头盔',
                survivor_armor: '幸存者护甲',
                survivor_boots: '幸存者靴子',
                
                // 狂战士套装
                berserker_mask: '狂战士面具',
                berserker_armor: '狂战士铠甲',
                berserker_gauntlets: '狂战士护手',
                
                // 暗影套装
                shadow_hood: '暗影兜帽',
                shadow_cloak: '暗影斗篷',
                shadow_boots: '暗影靴',
                
                // 元素法师套装
                elemental_hat: '元素法师帽',
                elemental_robe: '元素长袍',
                elemental_staff: '元素法杖',
                
                // 科技战士套装
                tech_helmet: '科技头盔',
                tech_exosuit: '科技外骨骼',
                tech_boots: '科技战靴'
            };
            
            return names[itemId] || itemId;
        }
        
        selectRarity() {
            const rand = Math.random();
            let cumulative = 0;
            
            for (const [rarity, rate] of Object.entries(this.dropRates)) {
                cumulative += rate;
                if (rand <= cumulative) return rarity;
            }
            
            return 'common';
        }
        
        collectEquipment(equipment) {
            // 添加到玩家背包
            const item = {
                id: equipment.itemId,
                name: equipment.itemName,
                setId: equipment.setId,
                rarity: equipment.rarity,
                equipped: false,
                timestamp: Date.now()
            };
            
            this.playerInventory.push(item);
            this.savePlayerInventory();
            
            // 显示获得信息
            window.gameEnhancements?.visualEffects?.createComboText(
                window.player?.x || 500,
                window.player?.y || 400,
                `获得: ${item.name}`,
                this.getRarityColor(item.rarity)
            );
            
            // 检查套装完成度
            this.checkSetCompletion(item.setId);
            
            console.log(`⚔️ 收集装备: ${item.name}`);
        }
        
        checkSetCompletion(setId) {
            const set = this.availableSets.find(s => s.id === setId);
            if (!set) return;
            
            const ownedItems = this.playerInventory.filter(item => 
                item.setId === setId && item.equipped
            );
            
            const ownedCount = ownedItems.length;
            
            // 检查套装奖励
            if (ownedCount >= 2 && set.bonuses[2]) {
                this.activateSetBonus(set, 2);
            }
            if (ownedCount >= 3 && set.bonuses[3]) {
                this.activateSetBonus(set, 3);
            }
            
            // 显示套装进度
            window.gameEnhancements?.visualEffects?.createEventNotification(
                `${set.name}: ${ownedCount}/${set.items.length}`,
                '#9370DB'
            );
        }
        
        activateSetBonus(set, pieces) {
            const bonus = set.bonuses[pieces];
            if (!bonus) return;
            
            // 检查是否已经激活
            const existingActive = this.activeSets.find(active => 
                active.setId === set.id && active.pieces === pieces
            );
            
            if (existingActive) return;
            
            // 激活套装效果
            bonus.effect();
            this.activeSets.push({
                setId: set.id,
                setName: set.name,
                pieces: pieces,
                bonusName: bonus.name,
                description: bonus.description
            });
            
            // 显示激活信息
            window.gameEnhancements?.visualEffects?.createEventNotification(
                `🎆 ${set.name} (${pieces}件)`,
                '#FFD700'
            );
            
            setTimeout(() => {
                window.gameEnhancements?.visualEffects?.createEventNotification(
                    bonus.name,
                    '#FF69B4'
                );
            }, 1500);
            
            console.log(`🎆 激活套装: ${set.name} (${pieces}件) - ${bonus.name}`);
        }
        
        // 套装效果实现
        applySurvivorSet2() {
            if (window.player) {
                window.player.maxHealth += 50;
                window.player.health = Math.min(window.player.health + 50, window.player.maxHealth);
                if (window.player.updateHealthUI) window.player.updateHealthUI();
                
                // 生命回复效果
                this.addPassiveEffect('health_regen', 2);
            }
        }
        
        applySurvivorSet3() {
            this.addPassiveEffect('damage_reduction', 0.3);
            if (window.player) {
                window.player.speed *= 1.25;
            }
            this.addPassiveEffect('death_revival', 0.5);
        }
        
        applyBerserkerSet2() {
            this.addPassiveEffect('attack_speed_bonus', 0.4);
            this.addPassiveEffect('kill_heal', 15);
        }
        
        applyBerserkerSet3() {
            if (window.player?.currentWeapon) {
                window.player.currentWeapon.damage *= 2;
            }
            this.addPassiveEffect('berserker_rage', true);
            this.addPassiveEffect('fear_immunity', true);
        }
        
        applyShadowSet2() {
            if (window.gameEnhancements?.dodgeSystem) {
                window.gameEnhancements.dodgeSystem.dodgeCooldown *= 0.5;
            }
            if (window.player) {
                window.player.speed *= 1.3;
            }
        }
        
        applyShadowSet3() {
            this.addPassiveEffect('backstab_crit', 1.0);
            this.addPassiveEffect('crit_damage_bonus', 3.0);
            this.addPassiveEffect('shadow_stealth', 3000);
        }
        
        applyElementalSet2() {
            this.addPassiveEffect('elemental_attacks', true);
        }
        
        applyElementalSet3() {
            this.addPassiveEffect('elemental_storm', true);
        }
        
        applyTechSet2() {
            if (window.player?.currentWeapon) {
                window.player.currentWeapon.maxAmmo *= 2;
                window.player.currentWeapon.totalAmmo *= 2;
                window.player.currentWeapon.reloadTime *= 0.5;
            }
        }
        
        applyTechSet3() {
            this.addPassiveEffect('auto_aim', true);
            this.addPassiveEffect('piercing_shots', true);
            this.addPassiveEffect('energy_shield', 100);
        }
        
        addPassiveEffect(type, value) {
            if (!window.setEffects) window.setEffects = {};
            window.setEffects[type] = value;
        }
        
        setupInventoryUI() {
            // 添加快捷键显示背包
            document.addEventListener('keydown', (e) => {
                if (e.code === 'KeyI' && !e.ctrlKey) {
                    e.preventDefault();
                    this.showInventoryUI();
                }
            });
        }
        
        showInventoryUI() {
            const inventoryDiv = document.createElement('div');
            inventoryDiv.id = 'inventoryUI';
            inventoryDiv.style.cssText = `
                position: fixed; top: 0; left: 0; width: 100%; height: 100%;
                background: rgba(0, 0, 0, 0.9); z-index: 20000;
                display: flex; align-items: center; justify-content: center;
                color: white; font-family: monospace;
            `;
            
            const setProgress = this.getSetProgress();
            
            inventoryDiv.innerHTML = `
                <div style="
                    max-width: 800px; max-height: 600px; padding: 30px;
                    background: linear-gradient(135deg, rgba(30, 30, 60, 0.95), rgba(60, 30, 60, 0.95));
                    border-radius: 15px; border: 3px solid #9370DB;
                    overflow-y: auto;
                ">
                    <h1 style="color: #9370DB; text-align: center; margin-bottom: 20px;">⚔️ 装备收藏</h1>
                    
                    <div style="display: flex; gap: 20px;">
                        <div style="flex: 1;">
                            <h3 style="color: #FFD700; margin-bottom: 15px;">🎒 背包装备 (${this.playerInventory.length})</h3>
                            <div style="max-height: 200px; overflow-y: auto; background: rgba(0,0,0,0.3); padding: 10px; border-radius: 5px;">
                                ${this.renderInventoryItems()}
                            </div>
                        </div>
                        
                        <div style="flex: 1;">
                            <h3 style="color: #FF69B4; margin-bottom: 15px;">🎆 激活套装 (${this.activeSets.length})</h3>
                            <div style="max-height: 200px; overflow-y: auto; background: rgba(0,0,0,0.3); padding: 10px; border-radius: 5px;">
                                ${this.renderActiveSets()}
                            </div>
                        </div>
                    </div>
                    
                    <div style="margin-top: 20px;">
                        <h3 style="color: #87CEEB; margin-bottom: 15px;">📊 套装进度</h3>
                        <div style="background: rgba(0,0,0,0.3); padding: 15px; border-radius: 5px;">
                            ${setProgress}
                        </div>
                    </div>
                    
                    <div style="text-align: center; margin-top: 20px;">
                        <button id="closeInventory" style="
                            background: linear-gradient(45deg, #555, #777);
                            border: none; color: white; padding: 10px 20px;
                            border-radius: 5px; cursor: pointer;
                        ">关闭 [I]</button>
                    </div>
                </div>
            `;
            
            document.body.appendChild(inventoryDiv);
            
            // 关闭事件
            document.getElementById('closeInventory').addEventListener('click', () => {
                this.closeInventoryUI(inventoryDiv);
            });
            
            // ESC或I键关闭
            const closeHandler = (e) => {
                if (e.code === 'Escape' || e.code === 'KeyI') {
                    e.preventDefault();
                    this.closeInventoryUI(inventoryDiv);
                    document.removeEventListener('keydown', closeHandler);
                }
            };
            document.addEventListener('keydown', closeHandler);
        }
        
        renderInventoryItems() {
            if (this.playerInventory.length === 0) {
                return '<div style="color: #999; text-align: center;">背包空空如也...</div>';
            }
            
            return this.playerInventory.map(item => `
                <div style="
                    padding: 8px; margin: 5px 0; 
                    background: rgba(${this.getRarityRGB(item.rarity)}, 0.2);
                    border-left: 3px solid ${this.getRarityColor(item.rarity)};
                    border-radius: 3px;
                ">
                    <div style="color: ${this.getRarityColor(item.rarity)}; font-weight: bold;">
                        ${item.name} ${item.equipped ? '✓' : ''}
                    </div>
                    <div style="color: #CCC; font-size: 12px;">
                        ${this.getSetByItemId(item.setId)?.name || '未知套装'}
                    </div>
                </div>
            `).join('');
        }
        
        renderActiveSets() {
            if (this.activeSets.length === 0) {
                return '<div style="color: #999; text-align: center;">暂无激活套装</div>';
            }
            
            return this.activeSets.map(set => `
                <div style="
                    padding: 10px; margin: 5px 0;
                    background: rgba(255, 215, 0, 0.1);
                    border-left: 3px solid #FFD700;
                    border-radius: 3px;
                ">
                    <div style="color: #FFD700; font-weight: bold;">
                        ${set.setName} (${set.pieces}件)
                    </div>
                    <div style="color: #FF69B4; font-size: 14px; margin: 2px 0;">
                        ${set.bonusName}
                    </div>
                    <div style="color: #CCC; font-size: 12px;">
                        ${set.description}
                    </div>
                </div>
            `).join('');
        }
        
        getSetProgress() {
            return this.availableSets.map(set => {
                const ownedItems = this.playerInventory.filter(item => item.setId === set.id);
                const ownedCount = ownedItems.length;
                const totalCount = set.items.length;
                const percentage = Math.floor((ownedCount / totalCount) * 100);
                
                return `
                    <div style="margin: 8px 0; padding: 8px; background: rgba(255,255,255,0.05); border-radius: 3px;">
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <span style="color: ${this.getRarityColor(set.rarity)}; font-weight: bold;">
                                ${set.name}
                            </span>
                            <span style="color: #CCC;">
                                ${ownedCount}/${totalCount} (${percentage}%)
                            </span>
                        </div>
                        <div style="
                            width: 100%; height: 8px; background: rgba(0,0,0,0.3);
                            border-radius: 4px; margin-top: 5px; overflow: hidden;
                        ">
                            <div style="
                                width: ${percentage}%; height: 100%;
                                background: linear-gradient(90deg, ${this.getRarityColor(set.rarity)}, ${this.getRarityColor(set.rarity)}88);
                                transition: width 0.3s ease;
                            "></div>
                        </div>
                    </div>
                `;
            }).join('');
        }
        
        closeInventoryUI(dialog) {
            dialog.style.animation = 'fadeOut 0.3s ease-out';
            setTimeout(() => {
                if (dialog.parentNode) {
                    document.body.removeChild(dialog);
                }
            }, 300);
        }
        
        getRarityColor(rarity) {
            const colors = {
                common: '#FFFFFF',
                rare: '#0088FF',
                epic: '#AA00FF',
                legendary: '#FFD700'
            };
            return colors[rarity] || colors.common;
        }
        
        getRarityRGB(rarity) {
            const rgbs = {
                common: '255, 255, 255',
                rare: '0, 136, 255',
                epic: '170, 0, 255',
                legendary: '255, 215, 0'
            };
            return rgbs[rarity] || rgbs.common;
        }
        
        getSetByItemId(setId) {
            return this.availableSets.find(set => set.id === setId);
        }
        
        savePlayerInventory() {
            try {
                localStorage.setItem('playerInventory', JSON.stringify(this.playerInventory));
                localStorage.setItem('activeSets', JSON.stringify(this.activeSets));
            } catch (error) {
                console.error('背包保存失败:', error);
            }
        }
        
        loadPlayerInventory() {
            try {
                const inventory = localStorage.getItem('playerInventory');
                const activeSets = localStorage.getItem('activeSets');
                
                if (inventory) {
                    this.playerInventory = JSON.parse(inventory);
                }
                
                if (activeSets) {
                    this.activeSets = JSON.parse(activeSets);
                    // 重新应用套装效果
                    this.activeSets.forEach(activeSet => {
                        const set = this.availableSets.find(s => s.id === activeSet.setId);
                        if (set && set.bonuses[activeSet.pieces]) {
                            set.bonuses[activeSet.pieces].effect();
                        }
                    });
                }
            } catch (error) {
                console.error('背包加载失败:', error);
            }
        }
        
        update(deltaTime) {
            // 更新套装效果
            this.updateSetEffects();
        }
        
        updateSetEffects() {
            if (!window.setEffects) return;
            
            // 生命回复
            if (window.setEffects.health_regen && window.player) {
                window.player.health = Math.min(
                    window.player.maxHealth,
                    window.player.health + window.setEffects.health_regen / 60 // 每秒回复
                );
                if (window.player.updateHealthUI) window.player.updateHealthUI();
            }
            
            // 狂战士愤怒
            if (window.setEffects.berserker_rage && window.player?.currentWeapon) {
                const healthRatio = window.player.health / window.player.maxHealth;
                const rageMultiplier = 1 + (1 - healthRatio) * 2; // 最高3倍
                
                if (!window.player.currentWeapon.baseDamage) {
                    window.player.currentWeapon.baseDamage = window.player.currentWeapon.damage / 2; // 因为已经有2倍了
                }
                
                window.player.currentWeapon.damage = Math.floor(
                    window.player.currentWeapon.baseDamage * 2 * rageMultiplier
                );
            }
        }
        
        getEquipmentStats() {
            return {
                inventoryCount: this.playerInventory.length,
                activeSets: this.activeSets.length,
                setCompletion: this.availableSets.map(set => ({
                    name: set.name,
                    owned: this.playerInventory.filter(item => item.setId === set.id).length,
                    total: set.items.length
                }))
            };
        }
    }
    
    // 全局初始化
    window.EquipmentSetSystem = EquipmentSetSystem;
    
    // 自动启动
    setTimeout(() => {
        if (!window.equipmentSetSystem && window.gameEngine) {
            window.equipmentSetSystem = new EquipmentSetSystem();
            window.equipmentSetSystem.initialize();
            
            // 集成到增强系统的装备收集
            if (window.gameEngine) {
                const originalUpdate = window.gameEngine.update.bind(window.gameEngine);
                
                window.gameEngine.update = function(deltaTime) {
                    originalUpdate(deltaTime);
                    
                    // 检查套装装备收集
                    this.powerUps.forEach((powerUp, index) => {
                        if (powerUp.type === 'set_equipment' && !powerUp.collected && window.player) {
                            const distance = Math.sqrt(
                                Math.pow(powerUp.x - window.player.x, 2) + 
                                Math.pow(powerUp.y - window.player.y, 2)
                            );
                            
                            if (distance < 30) {
                                window.equipmentSetSystem.collectEquipment(powerUp);
                                this.powerUps.splice(index, 1);
                            }
                        }
                    });
                    
                    // 更新套装系统
                    if (window.equipmentSetSystem) {
                        window.equipmentSetSystem.update(deltaTime);
                    }
                };
            }
            
            console.log('⚔️ 装备套装系统已加载');
        }
    }, 8000);
    
})();